/*
 * Funambol is a mobile platform developed by Funambol, Inc. 
 * Copyright (C) 2008 Funambol, Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission 
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE 
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Affero General Public License 
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 * 
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite 
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably 
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#ifndef INCL_ADDRESSBOOK_SYNC_SOURCE
#define INCL_ADDRESSBOOK_SYNC_SOURCE

#include "spds/AbstractSyncSourceConfig.h"

#include "client/CacheSyncSource.h"
#include "client/SQLKeyValueStore.h"

#include "base/util/StringBuffer.h"

#include "AddressBook/AddressBook.h"

#include "PersonDataConverter.h"

#include <semaphore.h>

#include <sqlite3.h>

/**
 * WIP
**/

class AddressBookSyncSource : public Funambol::CacheSyncSource {

private:

    sem_t sema;

    ABAddressBookRef addressbook;
    
    PersonDataConverter * pdc;
    
    ABAddressBookRef getAddressBook();
    
    char    * kvsUri,
            * kvsDatabase,
            * kvsTable, 
            * kvsUsername, 
            * kvsPassword;
    
    /**
     * Log and handle an error
     */
    void error(const char * msg);


    /**
     * Get the last modified time as a string for the given person
     *
     * @param person    - The person to work on
     *
     * @return          - A StringBuffer containing the string
     */
    const Funambol::StringBuffer getLastModificationTime(ABRecordRef person);
    
    
    void lock();
    void unlock();
   

public:

    AddressBookSyncSource(const char* name, Funambol::AbstractSyncSourceConfig* sc);
                        
    virtual ~AddressBookSyncSource();

    virtual Funambol::StringBuffer getItemSignature(Funambol::StringBuffer& key);

    /**
    * Get the content of an item given the key. It is used to populate
    * the SyncItem before the engine uses it in the usual flow of the sync.      
    *
    * @param key      the local key of the item
    * @param size     OUT: the size of the content
    */
    virtual void* getItemContent(Funambol::StringBuffer& key, size_t* size);
    
    /**
    * Get an array list containing all the StringBuffer keys of all items. 
    * Used for the sync requiring and exchange of all items and
    * for the sync that need to calculate the modification.
    * It has to return a new allocated Enumeration that is
    * freed by the CacheSyncSource
    */
    virtual Funambol::Enumeration* getAllItemList();      
    
    /**
     * Called by the sync engine to add an item that the server has sent.
     * The sync source is expected to add it to its database, then set the
     * key to the local key assigned to the new item. Alternatively
     * the sync source can match the new item against one of the existing
     * items and return that key.
     *
     * @param item    the item as sent by the server
     * @return SyncML status code
     */
    virtual int insertItem(Funambol::SyncItem& item);

    /**
     * Called by the sync engine to update an item that the source already
     * should have. The item's key is the local key of that item.
     *
     * @param item    the item as sent by the server
     * @return SyncML status code
     */
    virtual int modifyItem(Funambol::SyncItem& item);

    /**
     * Called by the sync engine to update an item that the source already
     * should have. The item's key is the local key of that item, no data is
     * provided.
     *
     * @param item    the item as sent by the server
     */
    virtual int removeItem(Funambol::SyncItem& item);   
   
    /**
     * Removes all the item of the sync source. It is called 
     * by the engine in the case of a refresh from server to clean      
     * all the client items before receiving the server ones.
     * It is called after the beginSync() method.
     *
     *@return 0 if the remote succeded.
     */
    virtual int removeAllItems();

    /**
     * Stop the current sync, flushing changes to the cache to the persistent store
     */
    void stopSync();

     /**
     * If getSyncMode() returns SYNC_REFRESH_FROM_SERVER, this function removed all sync items
     *
     * @return - 0 on success, an error otherwise
     */
    int beginSync();

    /**
    * In the first implementatation, in which serverStatusPackageEnded and 
    * clientStatusPackageEnded are not yet impelemented, the end sync
    * will udpate the whole cache status persistently.
    *
    * @param shouldUnlock   If false, this function will not unlock the semaphore ir uses
    */
    int endSync(bool shouldUnlock = true);       

// Static

public:
    /**
     * Initalize the SQLite database used by the cache
     *
     * @return Zero on success, non-zero on failure
     **/
    static int initializeDatabase();
    
    /**
     * Verify the SQLite database used by the cache exists
     *
     * @return Zero on success, non-zero on failure
     **/
    static int verifyDatabase();
    
private:

    /**
     * Get the path of the database file
     * 
     * @return A StringBuffer with the value.
     **/
    static Funambol::StringBuffer getDatabasePath();
    
    /**
     * Get the name of the table
     * 
     * @return A StringBuffer with the value
     **/
    static Funambol::StringBuffer getTableName();

    /**
     * Get the name of the value column
     * 
     * @return A StringBuffer with the value
     **/
    static Funambol::StringBuffer getValueColumnName();

    /**
     * Get the name of the name column
     * 
     * @return A StringBuffer with the value
     **/
    static Funambol::StringBuffer getKeyColumnName();

};

#endif
